﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Portal.Core;
using Portal.Web.Model;
using Portal.Systems.Model;
using Portal.Web.Utility;
using Portal.Utility;
using Portal.Workflow.Bussiness;
using System.Data;
using Portal.Xml.Utility;
using Portal.Admin.Home.Render.Template;
using System.IO;
using System.Collections;

namespace Portal.Systems.Render
{
    public class UpdateRoleRelationTemplateRenderBll
    {
        static void CheckPermission(string SiteId)
        {
            try
            {
                string UserId = WebSessionUtility.GetCurrentLoginUser().UserId;
                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CheckPermission(SiteId, SystemPermission.StaticId, SystemPermission.funcManage, SystemPermission.funcManage, UserId, true);
            }
            catch (Exception ex)
            {
                string ReturnData = "<div class=CssAccessDenied>" + ex.Message.ToString() + " <span class=CssBack><a href=\"javascript:history.back(-1);\">Quay lại</a></span></div>\r\n";
                throw new Exception(ReturnData);
            }
        }

        public static AjaxOut Draw(string SiteId)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                CheckPermission(SiteId);

                string RoleRelationTemplateId = (string)WebEnvironments.Request(SiteId, "RoleRelationTemplateId");
                RoleRelationTemplateCls 
                    oRoleRelationTemplateCls = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleRelationTemplateModel(SiteId, RoleRelationTemplateId);
                
                string XmlRelation = oRoleRelationTemplateCls.XmlData;
                DataSet dsCheck = new DataSet();
                dsCheck.ReadXml(new StringReader(XmlRelation));
                ArrayList ArrayListRemoved = new ArrayList();
                for (int iIndex = 0; iIndex < dsCheck.Tables[0].Rows.Count; iIndex++)
                {
                    string Id = (string)dsCheck.Tables[0].Rows[iIndex]["Id"];
                    string FromRoleId = (string)dsCheck.Tables[0].Rows[iIndex]["FromRoleId"];
                    string ToRoleId = (string)dsCheck.Tables[0].Rows[iIndex]["ToRoleId"];

                    RoleCls oFromRoleCls = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleModel(SiteId, FromRoleId);
                    RoleCls oToRoleCls = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleModel(SiteId, ToRoleId);
                    if (oFromRoleCls == null || oToRoleCls == null)
                    {
                        ArrayListRemoved.Add(Id);
                    }
                }

                for (int iIndex = 0; iIndex < ArrayListRemoved.Count; iIndex++)
                {
                    string Id = (string)ArrayListRemoved[iIndex];
                    DataView dv = new DataView(dsCheck.Tables[0], "Id='" + Id + "'", "", DataViewRowState.CurrentRows);
                    dv.Delete(0);
                }
                XmlRelation = dsCheck.GetXml();
                RoleCls[] Roles = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).ReadingRoles(SiteId, null, null);
                string SelectParentRoleText = "<select id=\"drpParentRole\">\r\n";
                string SelectChildRoleText = "<select id=\"drpChildRole\">\r\n";
                for (int iIndex = 0; iIndex < Roles.Length; iIndex++)
                {
                    string RoleId = (string)Roles[iIndex].RoleId;
                    string RoleName = (string)Roles[iIndex].RoleName;
                    SelectParentRoleText += " <option value=\""+RoleId+"\">"+RoleName+"</option>\r\n";
                    SelectChildRoleText += " <option value=\"" + RoleId + "\">" + RoleName + "</option>\r\n";
                }
                SelectParentRoleText += "</select>\r\n";
                SelectChildRoleText += "</select>\r\n";

                SiteParam OSiteParam = WebEnvironments.CreateSiteParam(SiteId);
                string ButtonIconRoot = WebConfig.GetButtonIconRoot(OSiteParam);
                string RetHtml =


                    "<script language=javascript>\r\n" +
                "     function ClientSaveRoleRelationTemplate(RoleRelationTemplateId) {\r\n" +
                "         SiteId='" + SiteId + "';\r\n" +
                "         RoleRelationTemplateName = document.getElementById(\"txtRoleRelationTemplate\").value;\r\n" +
                "         XmlData = document.getElementById(\"txtXmlRelation\").value;\r\n" +
                //"         SortIndex= document.getElementById(\"txtSortIndex\").value;\r\n" +
                "         AjaxOut = Portal.Systems.Render.UpdateRoleRelationTemplateRenderBll.ServerSideSaveRoleRelationTemplate(SiteId, RoleRelationTemplateId, RoleRelationTemplateName, XmlData).value;\r\n" +
                "         if (AjaxOut.Error) {\r\n" +
                "             alert(AjaxOut.InfoMessage);\r\n" +
                "             return;\r\n" +
                "         }\r\n" +
                "         alert(AjaxOut.InfoMessage);\r\n" +
                //"         ClientBack();\r\n"+
                "     }\r\n" +


                " function ClientAddRoleToRelationTemplate() { \r\n" +
                "         SiteId='" + SiteId + "';\r\n" +
                "         XmlData = document.getElementById(\"txtXmlRelation\").value;\r\n" +
                "         ParentRoleIndex = document.getElementById(\"drpParentRole\").selectedIndex;\r\n" +
                "         ParentRoleId = document.getElementById(\"drpParentRole\").options[ParentRoleIndex].value;\r\n" +
                "         SubRoleIndex = document.getElementById(\"drpChildRole\").selectedIndex;\r\n" +
                "         SubRoleId = document.getElementById(\"drpChildRole\").options[SubRoleIndex].value;\r\n" +
                "         XmlData = Portal.Systems.Render.UpdateRoleRelationTemplateRenderBll.ServerSideAddRoleToRelationTemplate(SiteId, XmlData, ParentRoleId, SubRoleId).value;\r\n" +
                "         if (XmlData.indexOf('ERROR') != -1) {\r\n" +
                "            alert(XmlData);\r\n" +
                "             return;\r\n" +
                "         } else {\r\n" +
                "             rValue = Portal.Systems.Render.UpdateRoleRelationTemplateRenderBll.ServerSideProcessXmlData(SiteId, XmlData).value;\r\n" +
                "             if (rValue.indexOf('ERROR') != -1) {\r\n" +
                "                 alert(rValue);\r\n" +
                "                 return;\r\n" +
                "             }\r\n" +
                "             document.getElementById(\"txtXmlRelation\").value = XmlData;\r\n" +
                "             document.getElementById(\"divRoleRelationContent\").innerHTML = rValue;\r\n" +
                "         }\r\n" +
                "     } \r\n" +

                " function ClientRemoveRoleRelation(Id) { \r\n" +
                "     SiteId='" + SiteId + "';\r\n" +
                "     if (confirm('Bạn đã chắc chắn loại bỏ chưa?') == false) return; \r\n" +
                "     XmlData = document.getElementById(\"txtXmlRelation\").value; \r\n" +
                "     XmlData = Portal.Systems.Render.UpdateRoleRelationTemplateRenderBll.ServerSideRemoveRelationTemplate(SiteId, XmlData, Id).value; \r\n" +
                "     if (XmlData.indexOf('ERROR') != -1) { \r\n" +
                "         alert(XmlData); \r\n" +
                "         return; \r\n" +
                "     } else { \r\n" +
                "         rValue = Portal.Systems.Render.UpdateRoleRelationTemplateRenderBll.ServerSideProcessXmlData(SiteId, XmlData).value; \r\n" +
                "         if (rValue.indexOf('ERROR') != -1) { \r\n" +
                "             alert(rValue); \r\n" +
                "             return; \r\n" +
                "         } \r\n" +
                "         document.getElementById(\"txtXmlRelation\").value = XmlData; \r\n" +
                "         document.getElementById(\"divRoleRelationContent\").innerHTML = rValue; \r\n" +
                "     } \r\n" +
                " } \r\n" +

                "   function ClientBack()\r\n" +
                "   {\r\n" +
                "       window.open('RoleRelationTemplate.aspx','_self');\r\n" +
                "   }\r\n" +
                "</script>\r\n" +

                    " <div class=DatabaseFunction>\r\n" +
                    "        <ul>\r\n" +
                    "            <li onclick=\"javascript:ClientSaveRoleRelationTemplate('"+RoleRelationTemplateId+"');\"><img class=image src=\"" + ButtonIconRoot + "/Save.png\"><div>Ghi lại</div></li>\r\n" +
                    "            <li onclick=\"javascript:ClientBack();\"><img class=image src=\"" + ButtonIconRoot + "/back.png\"><div>Quay lại</div></li>\r\n" +
                    "        </ul>\r\n" +
                    "  </div>\r\n" +
                    "<input type=hidden id=\"txtXmlRelation\" value=\"" + XmlRelation + "\">" +
                    "<div class=CssFormSaveUpdate>\r\n" +
                    "      <table>" +
                    "          <tr>" +
                    "              <td colspan=2 class=\"cssMergeRow\">CHỌN DANH SÁCH QUAN HỆ</td>" +
                    "          </tr>" +

                    "          <tr>" +
                    "              <td class=Col1>Tên quan hệ</td>" +
                    "              <td class=Col2><input class=textbox type=textbox id=txtRoleRelationTemplate value=\"" + oRoleRelationTemplateCls.RoleRelationTemplateName + "\"></td>" +
                    "          </tr>" +

                    "          <tr>" +
                    "              <td class=Col1>Vị trí cha:</td>" +
                    "              <td class=Col2>" + SelectParentRoleText + "</td>" +
                    "          </tr>" +

                    "          <tr>" +
                    "              <td class=Col1>Vị trí con:</td>" +
                    "              <td class=Col2>" + SelectChildRoleText + "</td>" +
                    "          </tr>" +

                    //"          <tr>" +
                    //"              <td class=Col1>Thứ tự:</td>" +
                    //"              <td class=Col2><input id=txtSortIndex value=\""+oRoleRelationTemplateCls.SortIndex+"\" type=textbox class=textbox></td>" +
                    //"          </tr>" +

                    "          <tr>" +
                    "              <td class=Col1></td>" +
                    "              <td class=Col2><input type=\"button\" class=\"button\" value=\"Đưa vào quan hệ\" onclick=\"javascript:ClientAddRoleToRelationTemplate();\"></td>" +
                    "          </tr>" +

                    "          <tr>" +
                    "              <td class=\"cssMergeRow\" colspan=2>DANH SÁCH QUAN HỆ</td>" +
                    "          </tr>" +

                    "          <tr>" +
                    "              <td class=Col1></td>" +
                    "              <td class=Col2><div id=\"divRoleRelationContent\">" + ServerSideProcessXmlData(SiteId, XmlRelation) + "</div></td>" +
                    "          </tr>" +

                    "      </table>" +
                    "</div>\r\n";

                OAjaxOut.HtmlContent = RetHtml;
                return OAjaxOut;
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage= ex.Message.ToString();
                OAjaxOut.HtmlContent = ex.Message.ToString();
            }
            return OAjaxOut;
        }

        [AjaxPro.AjaxMethod]
        public static string ServerSideAddRoleToRelationTemplate(string SiteId,string Xml,string ParentRoleId,string SubRoleId)
        {
            try
            {
                if (ParentRoleId.Equals(SubRoleId))
                {
                    throw new Exception("Hai vai trò không được trùng nhau!");
                }
                DataSet ds = new DataSet();
                if (String.IsNullOrEmpty(Xml))
                {
                    ds.Tables.Add("Info");
                    ds.Tables["Info"].Columns.Add("Id");
                    ds.Tables["Info"].Columns.Add("FromRoleId");
                    ds.Tables["Info"].Columns.Add("ToRoleId");
                }
                else
                {
                    ds.ReadXml(new StringReader(Xml));
                    if (ds.Tables.Count == 0)
                    {
                        ds.Tables.Add("Info");
                        ds.Tables["Info"].Columns.Add("Id");
                        ds.Tables["Info"].Columns.Add("FromRoleId");
                        ds.Tables["Info"].Columns.Add("ToRoleId");
                    }
                    DataView dv = new DataView(ds.Tables[0], "FromRoleId='" + ParentRoleId + "' and ToRoleId='" + SubRoleId + "'", "", DataViewRowState.CurrentRows);
                    if (dv.Count > 0)
                    {
                        throw new Exception("Đã tồn tại quan hệ này! Không đưa quan hệ này vào được!");
                    }
                }
                string Id = System.Guid.NewGuid().ToString();
                ds.Tables[0].Rows.Add(new object[]{
                        Id, ParentRoleId,SubRoleId
                    });
                return ds.GetXml();
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }


        [AjaxPro.AjaxMethod]
        public static string ServerSideRemoveRelationTemplate(string SiteId, string Xml, string Id)
        {
            try
            {
                DataSet ds = new DataSet();
                if (String.IsNullOrEmpty(Xml))
                {
                    ds.Tables.Add("Info");
                    ds.Tables["Info"].Columns.Add("Id");
                    ds.Tables["Info"].Columns.Add("FromRoleId");
                    ds.Tables["Info"].Columns.Add("ToRoleId");
                }
                else
                {
                    ds.ReadXml(new StringReader(Xml));
                    DataView dv = new DataView(ds.Tables[0], "Id='" + Id + "'", "", DataViewRowState.CurrentRows);
                    if (dv.Count > 0)
                    {
                        dv.Delete(0);
                    }
                }
                
                return ds.GetXml();
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public static string ServerSideProcessXmlData(string SiteId, string Xml)
        {
            try
            {
                if (string.IsNullOrEmpty(Xml)) return "";
                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(Xml));
                string Html = "";
                if (ds.Tables.Count > 0)
                {
                    Html = "<table>\r\n";
                    for (int iIndex = 0; iIndex < ds.Tables[0].Rows.Count; iIndex++)
                    {
                        string Id = (string)ds.Tables[0].Rows[iIndex]["Id"];
                        string FromRoleId = (string)ds.Tables[0].Rows[iIndex]["FromRoleId"];
                        string ToRoleId = (string)ds.Tables[0].Rows[iIndex]["ToRoleId"];
                        RoleCls oFromRoleCls = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleModel(SiteId, FromRoleId);
                        RoleCls oToRoleCls = SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).CreateRoleModel(SiteId, ToRoleId);
                        Html += "<tr>\r\n" +
                              "     <td>" + oFromRoleCls.RoleCode + " / " + oFromRoleCls.RoleName + "</td>\r\n" +
                              "     <td> => </td>\r\n" +
                              "     <td>" + oToRoleCls.RoleCode + " / " + oToRoleCls.RoleName + "</td>\r\n" +
                              "     <td><input type=\"button\" class=\"button\" value=\"loại bỏ\" onclick=\"javascript:ClientRemoveRoleRelation('" + Id + "');\"></td>\r\n" +
                              "</tr>\r\n";
                    }
                    Html += "</table>\r\n";
                }
                return Html;
            }
            catch (Exception ex)
            {
                return "ERROR: " + ex.Message.ToString();
            }
        }

        [AjaxPro.AjaxMethod]
        public AjaxOut ServerSideSaveRoleRelationTemplate(
            string SiteId,
            string RoleRelationTemplateId,
            string RoleRelationTemplateName,
            string XmlData)
        {
            AjaxOut OAjaxOut = new AjaxOut();
            try
            {
                WebSessionUtility.CheckSessionTimeOut();
                if (RoleRelationTemplateName.Trim().Length == 0)
                {
                    throw new Exception("Nhập tiêu đề quan hệ vị trí công việc!");
                }
                if (String.IsNullOrEmpty(XmlData))
                {
                    throw new Exception("Chưa xác định quan hệ!");
                }
                DataSet ds = new DataSet();
                ds.ReadXml(new StringReader(XmlData));
                if (ds.Tables.Count == 0)
                {
                    throw new Exception("Chưa xác định quan hệ!");
                }

                SystemBussinessUtility.CreateSystemsBussinessProcess(SiteId).SaveRoleRelationTemplate(null,SiteId, RoleRelationTemplateId, RoleRelationTemplateName, XmlData);
                OAjaxOut.InfoMessage = "Cập nhật quan hệ vị trí công việc thành công!";
            }
            catch (Exception ex)
            {
                OAjaxOut.Error = true;
                OAjaxOut.InfoMessage=ex.Message.ToString();
            }
            return OAjaxOut;
        }
    }
}